﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Jzy.BLL.Project;
using Jzy.Core.Common.Web;

using Jzy.Model.Project;
using System.Data;

using Jzy.Model.Mail;
using Jzy.BLL.Mail;
using Frame.Lib.Common;
using Frame.Lib.Utilities;
using Frame.Lib.Core.Attach;
using Frame.Lib.Enums;
using Frame.Lib.Core.Dict;


namespace Jzy.Web.Project.BugManage
{
    public partial class Edit : PageEdit
    {
        private PrjBugBO _prjBug = new PrjBugBO();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindDrp();
                if (PKID2 != null)
                {
                    DispInfo();
                }
                SetTitle();
            }


            this.EnableUpload();
            AddAttr();
        }


        private void SetTitle()
        {
            if (PKID2 == null)
            {
                imgTitle.Src = "../../Common/Images/common/tb-add.gif";
                litTitle.Text = "登记缺陷";
            }
            else
            {
                imgTitle.Src = "../../Common/Images/common/tb-change.gif";
                litTitle.Text = "修改缺陷";
            }
        }

        private void DispInfo()
        {
            PrjBugInfo info = _prjBug.GetInfo(PKID2);

            EntityUtil.SetControl(pnlMain, info);

            BindReceiveID();

            ReceiveID.SelectedValue = info.ReceiveID.ToString();

            if (info.PlanEndTime == DateTime.MinValue)
            {
                PlanEndTime.Text = "";
            }
            else
            {
                PlanEndTime.Text = info.PlanEndTime.ToString("yyyy-MM-dd");
            }

            rptPicture.DataSource = info.Pictures;
            rptPicture.DataBind();

            if (info.Pictures.Count > 0)
            {
                trImages.Visible = true;
            }
            else
            {
                trImages.Visible = false;
            }
        }

        private void AddAttr()
        {
            WebUtil.SetTimeBox(PlanEndTime, false);
            JSUtil.ClickBtn(lnkSave, btnSave);
            JSUtil.ClickBtn(lnkSaveCreate, btnSaveCreate);
            JSUtil.ClickBtn(lnkCancel, btnCancel);
        }

        protected void rptPicture_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            ImageBO picture = new ImageBO("PrjBugPicture");
            picture.Delete(Convert.ToInt32(e.CommandArgument));
            DispInfo();
        }

        private void BindDrp()
        {
            _prjBug.BindPrj(PrjID);

            WebUtil.BindListControlWithEnum(Priority, typeof(BugPriority));
            WebUtil.BindListControlWithEnum(Severity, typeof(BugSeverity));
            foreach (ListItem item in Severity.Items)
            {
                BugSeverity severity = (BugSeverity)int.Parse(item.Value);
                switch (severity)
                {
                    case BugSeverity.轻微:
                        item.Text = item.Text + "（可以工作）";
                        break;
                    case BugSeverity.严重:
                        item.Text = item.Text + "（不能工作）";
                        break;
                    case BugSeverity.中等:
                        item.Text = item.Text + "（干扰工作）";
                        break;

                }
            }

            DictBO dict = new DictBO();
            dict.BindListControl(TypeCode, (int)DictItem.缺陷类型);

            BindReceiveID();
        }

        private void BindReceiveID()
        {
            ProjectBO prj = new ProjectBO();
            DataTable dt = prj.GetPrjMembers(PrjID.SelectedValue);
            ReceiveID.DataSource = dt.DefaultView;
            ReceiveID.DataTextField = "UserName";
            ReceiveID.DataValueField = "UserID";
            ReceiveID.DataBind();

            ProjectInfo info = prj.GetInfo(PrjID.SelectedValue);
            ReceiveID.SelectedValue = info.PMID.ToString();
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            Save();
            Response.Redirect("RegList.aspx", true);
        }

        private void Save()
        {
            PrjBugInfo info = _prjBug.GetInfo(PKID2);
            string prjName = PrjID.SelectedItem.Text;
            prjName = prjName.Substring(0, prjName.IndexOf("("));

            if (Name.Text == "")
            {
                Name.Text = prjName;
            }

            EntityUtil.SetEntity(pnlMain, info);
            if (PKID2 == null)
            {
                info.Status = (int)BugStatus.新的;
            }
            info.InputTime = DateTime.Now;
            info.CreatorID = AppSession.UserID;
            info.CreatorName = AppSession.UserName;

            info.ReceiveName = ReceiveID.SelectedItem.Text;

            _prjBug.Save(info);

            //发送邮件
            if (chkMail.Checked)
            {
                MailInfo mailInfo = new MailInfo();
                mailInfo.CreatorID = AppSession.UserID;
                mailInfo.CreatorName = AppSession.UserName;
                mailInfo.InputTime = DateTime.Now;
                mailInfo.Name = "新增缺陷提醒";
                mailInfo.Content = "<div style='font-weight:bold;padding:10px 0px 10px 10px;'>相关项目：[" + prjName + "]</div>" +
                                   "<div style='padding:10px 0px 10px 10px;'>=========下面是缺陷描述==========</div>" +
                                   "<div style='padding:10px 0px 10px 10px;'>" + info.Remark + "</div>" +
                                   "<div style='padding:10px 0px 10px 10px;'>===============================</div>";
                mailInfo.RecieveIDs = "-" + ReceiveID.SelectedValue; ;//用户ID要为负的
                mailInfo.RecieveNames = ReceiveID.SelectedItem.Text;

                MailBO mail = new MailBO(AppSession.UserID);
                mail.Send(mailInfo, null, WriteMailMode.New);
            }

            ImageBO picture = new ImageBO("PrjBugPicture");
            UserImage userImage = new UserImage("PrjBugPicture");
            foreach (string key in Request.Files.Keys)
            {
                //判断图片格式
                string extention = System.IO.Path.GetExtension(Request.Files[key].FileName).ToLower();
                if (extention == ".jpg" || extention == ".png" || extention == ".gif" || extention == ".bmp")
                {
                    System.Drawing.Bitmap img = new System.Drawing.Bitmap(Request.Files[key].InputStream);
                    ImageInfo pictureInfo = new ImageInfo();
                    pictureInfo.Name = System.IO.Path.GetFileName(Request.Files[key].FileName);
                    pictureInfo.BindID = info.ID;
                    pictureInfo.InputTime = DateTime.Now;
                    pictureInfo.Width = img.Width;
                    pictureInfo.Height = img.Height;
                    pictureInfo.Size = (int)Request.Files[key].InputStream.Length;

                    pictureInfo.OriginImage = userImage.Save(Request.Files[key]);//只存原图

                    picture.Save(pictureInfo);
                }
                
            }

        }

        private void ClearInfo()
        {
            PKID2 = null;
            Name.Text = "";
            PlanEndTime.Text = "";
            Remark.Text = "";
            chkMail.Checked = false;
        }

        protected void PrjID_SelectedIndexChanged(object sender, EventArgs e)
        {
            BindReceiveID();
        }

        protected void btnSaveCreate_Click(object sender, EventArgs e)
        {
            Save();
            JSUtil.Alert("保存成功，请继续!");
            ClearInfo();
            SetTitle();
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            Response.Redirect("RegList.aspx", true);
        }
    }
}
